from face_det_feature import FaceDetFeature
from db_operate import FaceDB

import cv2
import numpy as np
import json
from datetime import datetime, timezone
import os


def main():
    faceDB = FaceDB("face.db")
    faceID = {}
    # 同步数据库所有人脸ID信息
    rows = faceDB.select_all_faceid()
    for row in rows:
        faceID[row[0]] = {"name":row[1], "num":row[2], "feature":np.array(json.loads(row[3]))}
    
    faceDetFeature = FaceDetFeature()
    
    #image_path = "./test_img/test.jpg"  # 测试图像
    file_paths = []
    for entry in os.listdir("./test_img1"):
        entry_path = os.path.join("./test_img1", entry)
        if os.path.isfile(entry_path):
            file_paths.append(entry_path)
    
    for image_path in file_paths:
        img = cv2.imread(image_path)
        coords,features = faceDetFeature.get_info(img)
        
        # 测试
        timestamp = int(datetime.now(timezone.utc).timestamp()*1000) # 精确到毫秒
        for f_array, coord in zip(features, coords):
            f_list = [float(x) for x in f_array]  # list(f_array) np.float32不能直接转
            f_json = json.dumps(f_list) #列表才能被序列化
            c_json = json.dumps(coord)
            # 找出ID，没有匹配就新增
            name = ""
            score = 0.0
            for key in faceID:
                score_temp = faceDetFeature.compare_features(faceID[key]["feature"], f_array)
                if score_temp>score:
                    score = score_temp
                    name = faceID[key]["name"]
            if score<0.4:
                # 数据库里面没有对应人脸
                cur_id = faceDB.get_faceid_max_id()+1
                name = str(cur_id)
                # 插入一条人脸ID
                faceDB.insert_faceid((name, 1, f_json))
                # 同步更新缓存
                faceID[cur_id] = {"name":name, "num":0, "feature":f_array}
                rows = faceDB.select_all_faceid()
                print("所有ID:")
                for row in rows:
                    print(row[0],row[1],row[2])
                print("\n")
            # 记录人脸
            faceDB.insert_faceRecord((f'./save_img/{timestamp}.jpg', name, c_json, f_json))
        cv2.imwrite(f'./save_img/{timestamp}.jpg', img)
        rows = faceDB.select_all_faceRecord()
        print("所有记录:")
        for row in rows:
            print(row[0],row[1],row[2],np.array(json.loads(row[3])),np.array(json.loads(row[4])).shape)
        print("\n")




if __name__ == "__main__":
    main()


